import * as userService from '../services/login';
import router from 'umi/router';
import {checkLogin, setLoginUser} from '../../../utils/authUtils';
import {message} from "antd";

export default {
  namespace: 'login',
  state:{
  },
  reducers: {
    'cacheLogin'(state, { payload: datas }) {
      setLoginUser(datas.obj);
      router.push("/admin/index");
    },
    modifyState(state, {payload: options}) {
      return {...state, ...options};
    }
  },
  effects: {
    *login({ payload: values }, { put, call }) {
      const data = yield call(userService.remoteCheckLogin, values);
      if(data.obj) {
        setLoginUser(data.obj);
        router.push("/admin/index");
      } else {
        message.error(data.message);
      }
    },
    *loginByUsername({payload: username}, {call}) {
      const data = yield call(userService.loginByUsername, username);
      if(data) {
        setLoginUser(data.obj);
        router.push("/admin/index");
      }
    }
  },
  subscriptions: {
    setup({history}) {
      return history.listen((location) => {
        if(location.pathname === "/login") {
          if(checkLogin()) {
            router.push("/admin/index");
          }
        }
      });
    }
  }
}
